<?php
namespace app\admin\controller;

use app\admin\controller\Base;

use app\admin\model\admin\User as UserModel;
use app\admin\service\admin\Auth as AuthService;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class Login extends Base
{

    /**
     * 登录
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): Json
    {
    	$model = new UserModel;
        if (($userInfo = $model->login($this->postData())) === false) {
            return $this->returnError($model->getError() ?: '登录失败');
        }
        return $this->returnSuccess([
            'userId' => (int)$userInfo['user_id'],
            'token' => $model->getToken()
        ], '登录成功');
    }

    /**
     * 退出登录
     * @return Json
     */
    public function logout(): Json
    {
        (new AuthService)->logout();
        // 清空登录状态
        return $this->returnSuccess('退出成功');
    }
}
